package com.example.springstack.springsecurity.advice;

import com.alibaba.fastjson.JSONObject;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Qiangfanghao
 * advice spring3.2捕获 自定义异常
 */
@ControllerAdvice
public class SpringControllerAdvice {

    /**
     * 捕获自定义异常 SystemException
     * 返回的结果为 将自定义的异常封装到 自定义ExceptionResult 用于异常的错误码 错误信息 以及时间戳
     */
    @ExceptionHandler(AccessDeniedException.class)
    public void handle(HttpServletRequest httpServletRequest
            , HttpServletResponse httpServletResponse
            , AccessDeniedException e) throws IOException, ServletException {
        //设置响应状态
        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
        //设置返回json字符串
        httpServletResponse.setContentType("application/json;charset=utf-8");
        //写数据
        PrintWriter writer = httpServletResponse.getWriter();
        JSONObject jo = new JSONObject();
        jo.put("status","403");
        jo.put("msg","权限不足");
        writer.write(jo.toJSONString());

        writer.flush();
        writer.close();

    }
}
